//
//  NDLoginView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/15.
//

import SwiftUI

struct NDLoginView: View {
    // MARK: - Environment
    @EnvironmentObject private var appState: NDAppState
    @Environment(\.presentationMode) var presentationMode
    
    // MARK: - State Properties
    @State private var phoneNumber: String = ""
    @State private var password: String = ""
    @State private var isCountdown = false
    @State private var countdownSeconds = 60
    @State private var countdownTimer: Timer?
    @State private var isPrivacyPolicyAccepted = true
    @State private var showPrivacyPolicy = false
    
    // MARK: - Computed Properties
    private var isPresented: Bool {
        presentationMode.wrappedValue.isPresented
    }
    
    private var isLoginEnabled: Bool {
        !phoneNumber.trimmingCharacters(in: .whitespaces).isEmpty &&
        !password.trimmingCharacters(in: .whitespaces).isEmpty &&
        isPrivacyPolicyAccepted
    }
    
    // MARK: - Body
    var body: some View {
        ZStack {
            contentView
        }
        .ignoresSafeArea(.all)
        .onDisappear(perform: stopCountdown)
        .background(
            ZStack {
                backgroundView
            }
        )
        .fullScreenCover(isPresented: $showPrivacyPolicy) {
            let urlString = NDAPIDomain.h5.rawValue + "potamoie"
            let webUrlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            NavigationView {
                NDWebView(
                    urlString: webUrlStr,
                    isFollowOrder: false,
                    isPresent: true
                )
            }
        }
        .onAppear {
            // 在视图出现时初始化
            phoneNumber = NDUserDefaults.shared.retrieveText(for: NDPhoneNumberKey) ?? ""
            
            if NDUserDefaults.shared.retrieveBoolean(for: NDMarketKey) == nil {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    NDTrackingTool.shared.requestIDFA { idfa in
                        NDEventAnallyticsTool.uploadMarketEvent()
                        NDUserDefaults.shared.saveBoolean(true, for: NDMarketKey)
                    }
                }
            }
            
            NDUserDefaults.shared.saveInteger(Int(Date().timeIntervalSince1970), for: NDloginStartTimeKey)
        }
        .ignoresSafeArea(.keyboard, edges: .bottom)
    }
}

// MARK: - Subviews
private extension NDLoginView {
    var backgroundView: some View {
        Image(WJAppEnvironment.shared.currentCountry == .india ? "sign up background" : "sign up background_id")
            .resizable()
            .scaledToFill()
            .ignoresSafeArea()
    }
    
    var contentView: some View {
        VStack(spacing: 0) {
            Spacer()
            Spacer()
            
            phoneNumberSection
            Spacer()
                .frame(height: 30)
            verificationCodeSection
            Spacer()
                .frame(height: 30)
            privacyPolicySection
            Spacer()
                .frame(height: 20)
            loginButton
            Spacer()
        }
        .padding(.horizontal, 24)
    }
    
    var phoneNumberSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(localizedString("phoneNumberTitle"))
                .font(.montserratRegular(16))
                .foregroundColor(.textPrimary)
            
            HStack {
                countryCode
                phoneNumberField
            }
            .frame(height: 52)
            .overlay(borderOverlay)
        }
    }
    
    var countryCode: some View {
        Group {
            let text = "+" + WJAppEnvironment.shared.currentCountry.numberCode
            Text(text)
                .font(.montserratBold(16))
                .foregroundColor(.textPrimary)
                .padding(.leading, 12)
        }
    }
    
    var phoneNumberField: some View {
        TextField(localizedString("phoneNumberPlaceholder"), text: $phoneNumber)
            .font(.montserratMedium(16))
            .foregroundColor(.textPrimary)
            .keyboardType(.numberPad)
            .onChange(of: phoneNumber) { newValue in
                phoneNumber = newValue.filter { $0.isNumber }
                print("phoneNumber: \(phoneNumber)")
            }
    }
    
    var verificationCodeSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Text(localizedString("VerificationCode"))
                    .font(.montserratRegular(16))
                    .foregroundColor(.textPrimary)
                
                Spacer()
                
                countdownButton
            }
            
            TextField(localizedString("VerificationCodePlaceholder"), text: $password)
                .font(.montserratMedium(16))
                .foregroundColor(.textPrimary)
                .frame(height: 52)
                .padding(.horizontal, 5)
                .keyboardType(.numberPad)
                .overlay(borderOverlay)
                .onChange(of: password) { newValue in
                    password = newValue.filter { $0.isNumber }
                    print("password: \(password)")
                }
        }
    }
    
    var countdownButton: some View {
        Group {
            if isCountdown {
                Text("\(countdownSeconds)s")
                    .font(.montserratMedium(16))
                    .foregroundColor(.textPrimary)
                    .frame(width: 60)
            } else {
                Button(action: requestVerCode) {
                    Text(localizedString("get code"))
                        .font(.montserratMedium(16))
                        .foregroundColor(.textPrimary)
                        .overlay(
                            Rectangle()
                                .frame(height: 1)
                                .foregroundColor(.textPrimary)
                                .offset(y: 8)
                        )
                }
            }
        }
    }
    
    var privacyPolicySection: some View {
        HStack(spacing: 5) {
            Spacer()
            privacyCheckbox
            privacyText
            Spacer()
        }
        .frame(maxWidth: .infinity)
    }
    
    var privacyCheckbox: some View {
        Button(action: togglePrivacyPolicy) {
            ZStack {
                Circle()
                    .stroke(
                        isPrivacyPolicyAccepted ? Color.primaryOrange : Color.grayMedium,
                        lineWidth: isPrivacyPolicyAccepted ? 4 : 2
                    )
                    .frame(width: 12, height: 12)
            }
            .frame(width: 20, height: 20, alignment: .center)
            .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    var privacyText: some View {
        Group {
            Text(localizedString("Read agree"))
                .foregroundColor(.textPrimary) +
            Text(" ") +
            Text(localizedString("login_Privacy Policy"))
                .foregroundColor(.textPrimary)
                .underline(true, color: .textPrimary)
        }
        .font(.montserratMedium(28))
        .lineLimit(1)
        .minimumScaleFactor(0.2)
        .fixedSize(horizontal: false, vertical: true)
        .overlay(
            GeometryReader { geometry in
                let fullText = localizedString("Read agree") + " " + localizedString("login_Privacy Policy")
                let privacyText = localizedString("login_Privacy Policy")
                
                if let range = fullText.range(of: privacyText) {
                    let nsRange = NSRange(range, in: fullText)
                    let privacyWidth = geometry.size.width * CGFloat(nsRange.length) / CGFloat(fullText.count)
                    let privacyOffset = geometry.size.width * CGFloat(nsRange.location) / CGFloat(fullText.count)
                    
                    Color.clear
                        .contentShape(Rectangle())
                        .frame(width: privacyWidth)
                        .offset(x: privacyOffset)
                        .onTapGesture(perform: handlePrivacyToDetail)
                }
            }
        )
        .onTapGesture(perform: handlePrivacyTextTap)
    }
    
    var loginButton: some View {
        Button(action: handleLogin) {
            Text(localizedString("LogIn"))
                .font(.montserratMedium(16))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity, minHeight: 48)
                .background(Color.backgroundPrimary)
                .clipShape(Capsule())
        }
        .buttonStyle(FullSizeButtonStyle())
    }
    
    var borderOverlay: some View {
        RoundedRectangle(cornerRadius: 12)
            .stroke(Color.black, lineWidth: 2)
    }
}

// MARK: - Actions
private extension NDLoginView {
    func togglePrivacyPolicy() {
        withAnimation(.easeInOut(duration: 0.2)) {
            isPrivacyPolicyAccepted.toggle()
        }
    }
    
    func handlePrivacyTextTap() {
        // 检测点击位置来决定是跳转还是选中
        // 这里简化处理，点击文本区域切换选中状态
        togglePrivacyPolicy()
    }
    
    func handlePrivacyToDetail() {
       
        showPrivacyPolicy = true
    }
    
    func handleLogin() {
        
//        guard !password.isEmpty else {
//            NDProgressHUD.showInfo("no verification code")
//            return
//        }
        
        guard isPrivacyPolicyAccepted else {
            NDProgressHUD.showInfo(localizedString("not aggree privacy"))
            return
        }
        
        NDProgressHUD.show()
        
        NDRequestManager.requestLogin(phoneNumber: phoneNumber, code: password) { loginModel, msg, error in
            if error == nil {
                if isPresented {
                    presentationMode.wrappedValue.dismiss()
                } else {
                    appState.rootView = .main
                }
                NDProgressHUD.dismiss()
                NDUserDefaults.shared.saveInteger(Int(Date().timeIntervalSince1970), for: NDloginEndTimeKey)
            } else {
                NDProgressHUD.showInfo(msg)
            }
        }
    }
    
    func requestVerCode() {
        UIApplication.shared.endEditing()
        NDProgressHUD.show()
        NDRequestManager.requestVerificationCode(phoneNumber: phoneNumber) { model, msg, error in
            if error == nil {
                self.startCountdown()
            }
            NDProgressHUD.showInfo(msg)
        }
    }
    
    func startCountdown() {
        startCountdownTimer()
    }
    
    func startCountdownTimer() {
        isCountdown = true
        countdownSeconds = 60
        
        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            if countdownSeconds > 1 {
                countdownSeconds -= 1
            } else {
                stopCountdown()
            }
        }
    }
    
    func stopCountdown() {
        countdownTimer?.invalidate()
        countdownTimer = nil
        isCountdown = false
        countdownSeconds = 60
    }
}

// MARK: - Color Extensions
extension Color {
    static let textPrimary = Color(hex: "#271F24")
    static let backgroundPrimary = Color(hex: "#271F24")
    static let primaryOrange = Color(hex: "#FD632B")
    static let grayMedium = Color(hex: "#AAAAAA")
}
